from docx import Document
from docx.oxml import OxmlElement
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.text.paragraph import Paragraph


def insert_image_after_paragraph(input_path, output_path, target_text, image_path, image_width_cm):
    doc = Document(input_path)
    found = False

    for paragraph in doc.paragraphs:
        print(paragraph.text)
        if target_text in paragraph.text:

            # 插入新段落并设置居中
            # new_paragraph = paragraph.insert_paragraph_after()
            new_paragraph =  insert_paragraph_after(paragraph=paragraph)
            new_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

            # 添加图片
            run = new_paragraph.add_run()
            run.add_picture(image_path, width=Cm(image_width_cm))
            found = True
            break

    if not found:
        print(f"未找到包含文本 '{target_text}' 的段落")
    else:
        doc.save(output_path)
        print(f"图片已插入，文档保存为: {output_path}")

def insert_paragraph_after(paragraph, text=None, style=None):
    """Insert a new paragraph after the given paragraph."""
    new_p = OxmlElement("w:p")
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)
    if text:
        new_para.add_run(text)
    if style is not None:
        new_para.style = style
    return new_para
# 使用示例
insert_image_after_paragraph(
    input_path='m:/jkl.docx',
    output_path='m:/output.docx',
    target_text="kafka的topic名称为：tracking-adas_periodicity_data _rt-topic",
    image_path='m:/tmp.png',
    image_width_cm=12
)